package com.lanou3g.hw0517;

import com.lanou3g.hw0517.controller.Controller;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;


@WebServlet(name = "registerServlet", urlPatterns = "/register")
public class registerServlet extends HttpServlet {
    private Controller controller = new Controller();

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=utf-8");
        // 拿到用户名和密码
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        String password1 = request.getParameter("password1");
        String nickname = request.getParameter("nickname");
        String hobby = request.getParameter("nickname");
        String gender = request.getParameter("gender");
        String reg = "";
        if (!password.equals(password1)) {
            reg = "注册失败,确认密码与密码不一致";
            request.setAttribute("reg", reg);
            request.getRequestDispatcher(request.getContextPath() + "/user/repetition.jsp").forward(request, response);
            return;
        }
        // 验证
        boolean isSuccess = controller.register(username, password, nickname, hobby, gender);
        // 根据验证结果构建验证信息
        String msg = "";
        String msg1 = "";
        if (isSuccess) {
            msg = "注册成功";
            request.setAttribute("msg", msg);
            request.getRequestDispatcher("/user/success.jsp").forward(request, response);
        } else {
            msg = "注册失败";
            msg1 = request.getContextPath() + "/user/register.jsp";
            //把消息放到request域中发送给jsp
            request.setAttribute("msg", msg);
            request.setAttribute("msg1", msg1);
            //请求转发
            request.getRequestDispatcher("/user/msg.jsp").forward(request, response);
        }

    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doPost(request, response);
    }
}
